package com.xrit.security;

import com.xrit.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;


public class UserService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //2.从数据库查询到的
        User user = findByUsername(username);

        //3.初始角色和权限的集合(GrantedAuthority：角色和权限共用接口),并添加角色和权限
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        //3.1添加1个角色(角色必须带"ROLE_")
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");
        authorities.add(authority);

        //添加1个权限(不带“ROLE_”的就是权限)
        authority = new SimpleGrantedAuthority("add");
        authorities.add(authority);

        //1.将security需要登陆用户信息添加进org.springframework.security.core.userdetails.User，并返回
        org.springframework.security.core.userdetails.User securityUser =
                new org.springframework.security.core.userdetails.User(username,user.getPassWord(),authorities);
        return securityUser;
    }

    /**
     * 假设从数据库查询
     */
    private User findByUsername (String userName){
        if("peng".equals(userName)) {
            User user = new User();
            user.setUserName("lin");
            user.setPassWord("{noop}$2a$10$kH8TLTeivHboJCCn7AHS7ungWaoZN5UdBSXWNbEadw/P8cLQnl/fy");
            return user;
        }
        return null;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("1234");
//        boolean matches = bCryptPasswordEncoder.matches("123","$2a$10$3YllQQo.LertsaJ/BcSeGOR/gESVfSoFXqXrEJC778QWCLQHUduhC");
        System.out.println(encode);

    }
}
